//
//  ZSSelectImageManage.m
//  CurriculumFactory
//
//  Created by apple on 2020/4/7.
//

#import "ZSSelectImageManage.h"
#import "BaseNavigationViewController.h"
#import "QDMultipleImagePickerPreviewViewController.h"//多选预览
#import "QDSingleImagePickerPreviewViewController.h"//单选

#import "WatermarkCameraController.h"//拍照

@interface ZSSelectImageManage ()<QMUIAlbumViewControllerDelegate,QMUIImagePickerViewControllerDelegate,QDMultipleImagePickerPreviewViewControllerDelegate,QDSingleImagePickerPreviewViewControllerDelegate>
@property(nonatomic,assign)BOOL isShow;

@end
@implementation ZSSelectImageManage

- (instancetype)init {
    self = [super init];
    if (self) {
        _isShow = NO;
        _maximumSelectImageCount=9;
        _contentType=QMUIAlbumContentTypeOnlyPhoto;
        _allowsMultipleSelection=NO;//默认单选
    }
    return self;
}
//显示选择 拍照还是 相册
- (void)show_choose {
    if (self.isShow) { return;}
    self.isShow = YES;
    
    @weakify(self);
  
    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleDestructive handler:^(QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        self_weak_.isShow = NO;
    }];
    QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"相册" style:QMUIAlertActionStyleDefault handler:^(QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        self_weak_.isShow = NO;
        [self_weak_ show_photo];
    }];
    
    QMUIAlertAction *action3 = [QMUIAlertAction actionWithTitle:@"拍照" style:QMUIAlertActionStyleDefault handler:^(QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        self_weak_.isShow = NO;
        [self_weak_ show_camera];
    }];
    QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle:QMUIAlertControllerStyleActionSheet];
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];

    QMUIVisualEffectView *visualEffectView = [[QMUIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    visualEffectView.foregroundColor = UIColorMakeWithRGBA(255, 255, 255, .6);// 一般用默认值就行，不用主动去改，这里只是为了展示用法
    alertController.mainVisualEffectView = visualEffectView;// 这个负责上半部分的磨砂
    visualEffectView = [[QMUIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    visualEffectView.foregroundColor = UIColorMakeWithRGBA(255, 255, 255, .6);// 一般用默认值就行，不用主动去改，这里只是为了展示用法
    alertController.cancelButtonVisualEffectView = visualEffectView;// 这个负责取消按钮的磨砂
    alertController.sheetHeaderBackgroundColor = nil;
    alertController.sheetButtonBackgroundColor = nil;
    [alertController showWithAnimated:YES];
}
#pragma mark 显示相机
- (void)show_camera {
    WatermarkCameraController *controller = [[WatermarkCameraController alloc] init];
//    controller.modalPresentationStyle=0;
    @weakify(self);
      controller.shot = ^(UIImage *image) {
          @strongify(self);
          if (image==nil) {
              return;
          }
          NSArray *images = @[image];
          if (self.completeBlock) {
              self.completeBlock(images);
          }
      };
     UIViewController * current_controller= [AppTools zs_getCurrentViewController];
    [current_controller presentViewController:controller animated:NO completion:nil];
}
- (void)show_photo {
     QMUIAlbumViewController *albumViewController = [[QMUIAlbumViewController alloc] init];
      albumViewController.albumViewControllerDelegate = self;
      albumViewController.contentType = self.contentType;
      albumViewController.title = @"选择照片";
      albumViewController.view.tag =  1048;
      BaseNavigationViewController *navigationController = [[BaseNavigationViewController alloc] initWithRootViewController:albumViewController];
      // 获取最近发送图片时使用过的相簿，如果有则直接进入该相簿
      [albumViewController pickLastAlbumGroupDirectlyIfCan];
       UIViewController *controlelr= [AppTools zs_getCurrentViewController];
       navigationController.modalPresentationStyle=0;
      [controlelr presentViewController:navigationController animated:YES completion:NULL];
}


#pragma mark - <QMUIAlbumViewControllerDelegate>
- (QMUIImagePickerViewController *)imagePickerViewControllerForAlbumViewController:(QMUIAlbumViewController *)albumViewController {
    QMUIImagePickerViewController *imagePickerViewController = [[QMUIImagePickerViewController alloc] init];
    imagePickerViewController.imagePickerViewControllerDelegate = self;
    /// 最多可以选择的图片数，默认为无符号整形数的最大值，相当于没有限制
    imagePickerViewController.maximumSelectImageCount = self.maximumSelectImageCount;
    imagePickerViewController.view.tag = albumViewController.view.tag;
#pragma mark 是否允许图片多选，默认为 YES。如果为 NO，则不显示 checkbox 和底部工具栏。
    imagePickerViewController.allowsMultipleSelection = self.allowsMultipleSelection;//单选多选
 
    return imagePickerViewController;
}

#pragma mark QMUIImagePickerViewControllerDelegate
/**
*  多选模式下选择图片完毕后被调用（点击 sendButton 后被调用），单选模式下没有底部发送按钮，所以也不会走到这个delegate
*
*  @param imagePickerViewController 对应的 QMUIImagePickerViewController
*  @param imagesAssetArray          包含被选择的图片的 QMUIAsset 对象的数组。
*/
- (void)imagePickerViewController:(QMUIImagePickerViewController *)imagePickerViewController didFinishPickingImageWithImagesAssetArray:(NSMutableArray<QMUIAsset *> *)imagesAssetArray {
    // 储存最近选择了图片的相册，方便下次直接进入该相册
    [QMUIImagePickerHelper updateLastestAlbumWithAssetsGroup:imagePickerViewController.assetsGroup ablumContentType:self.contentType userIdentify:nil];
    [self setctedImages:imagesAssetArray];
}

#pragma mark  创建一个 ImagePickerPreviewViewController 用于预览图片
- (QMUIImagePickerPreviewViewController *)imagePickerPreviewViewControllerForImagePickerViewController:(QMUIImagePickerViewController *)imagePickerViewController  {
    if (self.allowsMultipleSelection) {
#pragma mark 多选预览
         QDMultipleImagePickerPreviewViewController *imagePickerPreviewViewController =[[QDMultipleImagePickerPreviewViewController alloc] init];
       imagePickerPreviewViewController.delegate = self;
       imagePickerPreviewViewController.maximumSelectImageCount = self.maximumSelectImageCount;
       imagePickerPreviewViewController.assetsGroup = imagePickerViewController.assetsGroup;
       imagePickerPreviewViewController.view.tag = imagePickerViewController.view.tag;
        return imagePickerPreviewViewController;
    } else {
#pragma mark 单选预览
        QDSingleImagePickerPreviewViewController *imagePickerPreviewViewController = [[QDSingleImagePickerPreviewViewController alloc] init];
       imagePickerPreviewViewController.delegate = self;
       imagePickerPreviewViewController.assetsGroup = imagePickerViewController.assetsGroup;
       imagePickerPreviewViewController.view.tag = imagePickerViewController.view.tag;
       return imagePickerPreviewViewController;
    }
}
#pragma mark - 单选代理 <QDSingleImagePickerPreviewViewControllerDelegate>
- (void)imagePickerPreviewViewController:(QDSingleImagePickerPreviewViewController *)imagePickerPreviewViewController didSelectImageWithImagesAsset:(QMUIAsset *)imageAsset {
    // 储存最近选择了图片的相册，方便下次直接进入该相册
    [QMUIImagePickerHelper updateLastestAlbumWithAssetsGroup:imagePickerPreviewViewController.assetsGroup ablumContentType:self.contentType userIdentify:nil];
//    [imageAsset requestImageData:^(NSData *imageData, NSDictionary<NSString *,id> *info, BOOL isGif, BOOL isHEIC) {
//        UIImage *targetImage = nil;
//        if (isGif) {
//            targetImage = [UIImage qmui_animatedImageWithData:imageData];
//        } else {
//            targetImage = [UIImage imageWithData:imageData];
//            if (isHEIC) {
//                // iOS 11 中新增 HEIF/HEVC 格式的资源，直接发送新格式的照片到不支持新格式的设备，照片可能会无法识别，可以先转换为通用的 JPEG 格式再进行使用。
//                // 详细请浏览：https://github.com/Tencent/QMUI_iOS/issues/224
//                targetImage = [UIImage imageWithData:UIImageJPEGRepresentation(targetImage, 1)];
//            }
//        }
//
//    }];
    NSArray * imagesAssetArray = @[imageAsset];
    [self setctedImages:imagesAssetArray];
}

#pragma mark -多选预览代理 <QDMultipleImagePickerPreviewViewControllerDelegate>

- (void)imagePickerPreviewViewController:(QDMultipleImagePickerPreviewViewController *)imagePickerPreviewViewController sendImageWithImagesAssetArray:(NSMutableArray<QMUIAsset *> *)imagesAssetArray {
    // 储存最近选择了图片的相册，方便下次直接进入该相册
    [QMUIImagePickerHelper updateLastestAlbumWithAssetsGroup:imagePickerPreviewViewController.assetsGroup ablumContentType:self.contentType userIdentify:nil];
    [self setctedImages:imagesAssetArray];
}

- (void)setctedImages:(NSArray *)imagesAssetArray {
    NSMutableArray *images = [NSMutableArray new];
    for (QMUIAsset * asset in imagesAssetArray) {
        UIImage *image = [asset originImage];
        [images addObject:image];
    }
    if (self.completeBlock) {
           self.completeBlock(images);
       }
//    QMUIAsset * asset=imagesAssetArray.firstObject;
//    [self getVideoAsset:asset.phAsset];

    
    
    
    
   
}
//获取视频地址
- (void)getVideoAsset:(PHAsset *)asset {
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    options.version = PHImageRequestOptionsVersionCurrent;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    @weakify(self);
    PHImageManager *manager = [PHImageManager defaultManager];
    [manager requestAVAssetForVideo:asset
                            options:options
                      resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        // 获取到的url不全 /var/mobile/Media/DCIM/105APPLE/IMG_5567.MOV
        //正确的视频全地址 file:///private/var/mobile/Media/DCIM/100APPLE/IMG_0049.MOV,
        //一定要加前缀 private，视频主路径名前缀 文章详解：https://www.feng.com/post/8259350
        AVURLAsset *urlAsset = (AVURLAsset *)asset;
        NSString * videoFilePath= urlAsset.URL.filePathURL.path;
        if (![videoFilePath hasPrefix:@"file:///private"]) {
            videoFilePath = [@"file:///private" stringByAppendingString:videoFilePath];
        }
        @strongify(self);
        // 视频数据
        NSLog(@"视频地址 %@",videoFilePath);
         if (self.completePathBlock) {
            self.completePathBlock(videoFilePath);
        }
    }];
}




@end
